package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.UserLocation;
import com.tanhua.service.UserLocationApi;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author げっしょく
 * @date 2021/10/31
 */
@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //                                 用户id          经度              纬度             地理位置信息
    @Override
    public Boolean saveOrUpdateAddr(Long userId, Double longitude, Double latitude, String addrStr) {
        try {
            //查找条件
            Query query = Query.query(Criteria.where("userId").is(userId));
            //查找当前用户的位置信息
            UserLocation u = mongoTemplate.findOne(query, UserLocation.class);
            if (u == null) {
                //没有位置信息就进行保存
                u = new UserLocation();
                u.setUserId(userId);
                GeoJsonPoint geoJsonPoint = new GeoJsonPoint(longitude, latitude);
                u.setLocation(geoJsonPoint);
                u.setAddress(addrStr);
                u.setCreated(System.currentTimeMillis());
                u.setUpdated(System.currentTimeMillis());
                u.setLastUpdated(System.currentTimeMillis());
                mongoTemplate.save(u);
            } else {
                //有位置信息就对位置信息进行更新
                Update update = new Update().set("location", new GeoJsonPoint(longitude, latitude))
                        .set("updated", System.currentTimeMillis())
                        .set("lastUpdated", u.getUpdated())
                        .set("address", addrStr);
                mongoTemplate.updateFirst(query, update, UserLocation.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public List<Long> queryNearby(Long id, Double distance) {
        //根据用户id获取地理位置
        Query userId = Query.query(Criteria.where("userId").is(id));
        UserLocation userLocation = mongoTemplate.findOne(userId, UserLocation.class);
        if (userLocation == null) {
            return null;
        }
        //以当前用户位置绘制原点
        GeoJsonPoint location = userLocation.getLocation();
        //获得半径(以公里为单位, 传过来的却是以米为单位)
        Distance distance1 = new Distance(distance / 1000, Metrics.KILOMETERS);
        //画圆(以当前用户为中心点, distance1位半径)
        Circle circle = new Circle(location, distance1);
        //查询范围内的用户信息
        Query query = Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocations = mongoTemplate.find(query, UserLocation.class);
        List<Long> collect = userLocations.stream().map(u -> u.getUserId()).collect(Collectors.toList());
        return collect;
    }
}
